/**
 * 观点卡片组件
 * 展示单个AI模型生成的观点，支持展开/收起、评分、编辑等功能
 */

import React, { useState } from 'react';
import { Card, Tag, Progress, Button, Space, Tooltip, Rate, Collapse, Spin, Alert } from 'antd';
import {
  CheckCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
  ReloadOutlined,
  StarOutlined,
  ThunderboltOutlined,
  BulbOutlined,
  HeartOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { Viewpoint, PerspectiveType } from '@/types/brainstorm';
import './style.css';

const { Panel } = Collapse;

interface ViewpointCardProps {
  viewpoint: Viewpoint;
  selected?: boolean;
  onSelect?: (viewpointId: string) => void;
  onEdit?: (viewpoint: Viewpoint) => void;
  onRegenerate?: (viewpointId: string) => void;
  onRate?: (viewpointId: string, rating: number) => void;
}

export const ViewpointCard: React.FC<ViewpointCardProps> = ({
  viewpoint,
  selected = false,
  onSelect,
  onEdit,
  onRegenerate,
  onRate,
}) => {
  const [userRating, setUserRating] = useState<number>(0);
  const [expanded, setExpanded] = useState<boolean>(false);

  // 获取模型显示名称
  const getModelDisplayName = (model: string): string => {
    const modelNames: Record<string, string> = {
      'gpt-4': 'GPT-4',
      'claude': 'Claude',
      'deepseek': 'DeepSeek',
      'qwen': '通义千问',
    };
    return modelNames[model] || model;
  };

  // 获取视角显示信息
  const getPerspectiveInfo = (
    perspective: PerspectiveType
  ): { name: string; icon: React.ReactNode; color: string } => {
    const info: Record<PerspectiveType, { name: string; icon: React.ReactNode; color: string }> = {
      rational: {
        name: '理性分析',
        icon: <ThunderboltOutlined />,
        color: '#1890ff',
      },
      emotional: {
        name: '情感共鸣',
        icon: <HeartOutlined />,
        color: '#eb2f96',
      },
      innovative: {
        name: '创新思维',
        icon: <BulbOutlined />,
        color: '#722ed1',
      },
      popular: {
        name: '大众实用',
        icon: <TeamOutlined />,
        color: '#52c41a',
      },
    };
    return info[perspective];
  };

  const perspectiveInfo = getPerspectiveInfo(viewpoint.perspective);

  // 处理用户评分
  const handleUserRate = (value: number) => {
    setUserRating(value);
    onRate?.(viewpoint.id, value);
  };

  // 渲染卡片标题
  const renderTitle = () => (
    <div className="viewpoint-card-title">
      <Space>
        <Tag color="blue">{getModelDisplayName(viewpoint.model)}</Tag>
        <Tag color={perspectiveInfo.color} icon={perspectiveInfo.icon}>
          {perspectiveInfo.name}
        </Tag>
      </Space>
      {viewpoint.generating && (
        <Spin indicator={<LoadingOutlined spin />} size="small" />
      )}
      {viewpoint.completed && (
        <Tooltip title="生成完成">
          <CheckCircleOutlined style={{ color: '#52c41a', fontSize: '16px' }} />
        </Tooltip>
      )}
      {viewpoint.error && (
        <Tooltip title={viewpoint.error}>
          <ExclamationCircleOutlined style={{ color: '#ff4d4f', fontSize: '16px' }} />
        </Tooltip>
      )}
    </div>
  );

  // 渲染AI评分
  const renderAIScore = () => {
    if (!viewpoint.completed || !viewpoint.aiScore) return null;

    return (
      <div className="ai-score-section">
        <div className="score-header">
          <StarOutlined style={{ color: '#faad14' }} />
          <span className="score-label">AI综合评分</span>
          <span className="score-value">{viewpoint.aiScore}</span>
        </div>
        <div className="score-details">
          <div className="score-item">
            <span className="score-item-label">相关性</span>
            <Progress
              percent={viewpoint.scoreDetails.relevance}
              size="small"
              strokeColor="#1890ff"
              showInfo={false}
            />
            <span className="score-item-value">{viewpoint.scoreDetails.relevance}</span>
          </div>
          <div className="score-item">
            <span className="score-item-label">新颖性</span>
            <Progress
              percent={viewpoint.scoreDetails.novelty}
              size="small"
              strokeColor="#722ed1"
              showInfo={false}
            />
            <span className="score-item-value">{viewpoint.scoreDetails.novelty}</span>
          </div>
          <div className="score-item">
            <span className="score-item-label">可行性</span>
            <Progress
              percent={viewpoint.scoreDetails.feasibility}
              size="small"
              strokeColor="#52c41a"
              showInfo={false}
            />
            <span className="score-item-value">{viewpoint.scoreDetails.feasibility}</span>
          </div>
          <div className="score-item">
            <span className="score-item-label">影响力</span>
            <Progress
              percent={viewpoint.scoreDetails.impact}
              size="small"
              strokeColor="#faad14"
              showInfo={false}
            />
            <span className="score-item-value">{viewpoint.scoreDetails.impact}</span>
          </div>
        </div>
        {viewpoint.scoreReason && (
          <div className="score-reason">
            <span className="score-reason-label">评分理由：</span>
            <span>{viewpoint.scoreReason}</span>
          </div>
        )}
      </div>
    );
  };

  // 渲染观点内容
  const renderContent = () => {
    if (viewpoint.generating) {
      return (
        <div className="generating-content">
          <Spin tip="AI正在生成观点..." />
          {viewpoint.content && (
            <div className="stream-content">{viewpoint.content}</div>
          )}
        </div>
      );
    }

    if (viewpoint.error) {
      return (
        <Alert
          message="生成失败"
          description={viewpoint.error}
          type="error"
          showIcon
          action={
            <Button size="small" danger onClick={() => onRegenerate?.(viewpoint.id)}>
              重新生成
            </Button>
          }
        />
      );
    }

    if (!viewpoint.completed) {
      return <div className="empty-content">暂无内容</div>;
    }

    return (
      <div className="viewpoint-content">
        {/* 核心观点 */}
        <div className="core-viewpoint">
          <div className="section-title">💡 核心观点</div>
          <div className="section-content">{viewpoint.coreViewpoint}</div>
        </div>

        {/* 论据列表 */}
        {viewpoint.arguments && viewpoint.arguments.length > 0 && (
          <div className="arguments-section">
            <div className="section-title">📌 支撑论据</div>
            <ul className="arguments-list">
              {viewpoint.arguments.map((arg, index) => (
                <li key={index} className="argument-item">
                  {arg}
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* 可折叠的详细信息 */}
        <Collapse
          ghost
          activeKey={expanded ? ['details'] : []}
          onChange={(keys) => setExpanded(keys.includes('details'))}
        >
          <Panel header="查看更多详情" key="details">
            {/* 适用场景 */}
            {viewpoint.scenario && (
              <div className="scenario-section">
                <div className="section-title">🎯 适用场景</div>
                <div className="section-content">{viewpoint.scenario}</div>
              </div>
            )}

            {/* 预期效果 */}
            {viewpoint.expectedEffect && (
              <div className="effect-section">
                <div className="section-title">✨ 预期效果</div>
                <div className="section-content">{viewpoint.expectedEffect}</div>
              </div>
            )}
          </Panel>
        </Collapse>

        {/* AI评分 */}
        {renderAIScore()}

        {/* 用户评分 */}
        <div className="user-rating-section">
          <span className="rating-label">你的评价：</span>
          <Rate
            value={userRating}
            onChange={handleUserRate}
            style={{ fontSize: '16px' }}
          />
        </div>
      </div>
    );
  };

  // 渲染操作按钮
  const renderActions = () => {
    const actions: React.ReactNode[] = [];

    if (onSelect) {
      actions.push(
        <Button
          key="select"
          type={selected ? 'primary' : 'default'}
          size="small"
          onClick={() => onSelect(viewpoint.id)}
        >
          {selected ? '已选择' : '选择'}
        </Button>
      );
    }

    if (onEdit && viewpoint.completed) {
      actions.push(
        <Button
          key="edit"
          size="small"
          icon={<EditOutlined />}
          onClick={() => onEdit(viewpoint)}
        >
          编辑
        </Button>
      );
    }

    if (onRegenerate && !viewpoint.generating) {
      actions.push(
        <Button
          key="regenerate"
          size="small"
          icon={<ReloadOutlined />}
          onClick={() => onRegenerate(viewpoint.id)}
        >
          重新生成
        </Button>
      );
    }

    return actions.length > 0 ? actions : null;
  };

  return (
    <Card
      className={`viewpoint-card ${selected ? 'selected' : ''} ${
        viewpoint.generating ? 'generating' : ''
      }`}
      title={renderTitle()}
      actions={renderActions() || undefined}
      bordered
      hoverable={!viewpoint.generating}
    >
      {renderContent()}
    </Card>
  );
};
